package org.zoomdev.zoom.web.router;

import org.zoomdev.zoom.common.exceptions.ZoomException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 解析大括号的模式
 * <p>
 * /a/{b}/{c}
 *
 * @author jzoom
 */
public final class RouterParameterRule {

    public static final String ERROR = "url变量的规则为{^[a-zA-Z][a-zA-Z0-9_]*$}";
    private static final Pattern PATTERN = Pattern.compile("\\{([^\\}]+)\\}");
    private static final Pattern CORRECT_PATTERN = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]*$");

    public String[] getParameterNames(String key) {

        if (!match(key)) {
            return null;
        }

        if (key.startsWith("/")) {
            key = key.substring(1);
        }
        String[] parts = key.split("/");
        String[] names = new String[parts.length];
        int maxIndex = -1;
        for (int i = 0; i < parts.length; ++i) {
            String name = getParameterName(parts[i]);
            if (name != null) {
                names[i] = name;
                maxIndex = i;
            }
        }

        if (maxIndex < 0) {
            return null;
        }

        return cutNames(names, maxIndex);
    }

    public String getParameterName(String value) {
        Matcher matcher = PATTERN.matcher(value);
        if (matcher.matches()) {
            String realValue = matcher.group(1);
            if (!CORRECT_PATTERN.matcher(realValue).matches()) {
                throw new ZoomException(ERROR);
            }
            return realValue;
        }
        return null;
    }

    public boolean match(String url) {
        return url.contains("{");
    }

    private String[] cutNames(String[] names, int maxIndex) {
        if (maxIndex == names.length - 1) {
            return names;
        }

        String[] ret = new String[maxIndex + 1];
        System.arraycopy(names, 0, ret, 0, maxIndex + 1);
        return ret;
    }

}
